#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    : /counter_coruntine.py
@Time    : 2021-05-19 14:43:23
@Author  : Gray Snail
@Version : 1.0
@Contact : shtao2011@sina.com
@License : Copyright (c) 2021 Gray Snail
@Desc    : None
'''

# sleep 还是会 block，总用时 20s
# 由于 Schedule 存在，任务可以交替进行


from time import sleep
import time
from collections import deque


def count_down(n):
    while n > 0:
        print('Down', n)
        sleep(1)
        yield  # 交出执行权
        n -= 1


def count_up(n):
    x = 0
    while x < n:
        print('Up', x + 1)
        sleep(1)
        yield
        x += 1


class Scheduler(object):
    # 检测活跃任务并执行
    def __init__(self):
        self.ready = deque()
        self.current = None

    def new_task(self, coro):
        # coro 必须是生成器
        self.ready.append(coro)

    def run(self):
        while self.ready:
            self.current = self.ready.popleft()
            try:
                # send 属于生成器语法
                self.current.send(None)
                self.ready.append(self.current)

            except StopIteration:
                pass


if __name__ == '__main__':

    s = time.time()
    scheduler = Scheduler()
    scheduler.new_task(count_down(5))
    scheduler.new_task(count_up(15))

    scheduler.run()
    print(time.time() - s)
